<script setup>
import { ref, onMounted } from 'vue'
import { getUserOrders } from '../../api/user'
import { listDoctors, listPackages } from '../../api/admin'
import { updateOrderStatus } from '../../api/common'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../../store/auth'
import { ElMessage, ElMessageBox } from 'element-plus'

const auth = useAuthStore()
const router = useRouter()
const list = ref([])
const total = ref(0)
const query = ref({ status: '', orderType: '', page: 1, size: 10 })
const loading = ref(false)
const doctorNameMap = ref({})
const packageNameMap = ref({})
// 数字状态映射
const statusMap = { 1: '待确认', 2: '已确认', 3: '已完成', 4: '已取消' }
const statusTagType = { 1: 'warning', 2: 'info', 3: 'success', 4: 'danger' }

const fetchList = async () => {
  loading.value = true
  try {
    const data = await getUserOrders(auth.currentId, { status: (query.value.status === '' ? undefined : query.value.status), orderType: query.value.orderType || undefined, page: query.value.page, size: query.value.size })
    list.value = data.list || []
    total.value = data.total || 0
  } finally { loading.value = false }
}

const cancelOrder = async (row) => {
  if (row.status === 3 || row.status === 4) return
  try {
    await ElMessageBox.confirm('确定要取消该预约吗？', '取消预约', { type: 'warning' })
    await updateOrderStatus(row.orderId, { status: 4 })
    ElMessage.success('已取消预约')
    fetchList()
  } catch (e) {
    // 用户点击取消或请求失败
  }
}

onMounted(async () => {
  try {
    const [dsRes, psRes] = await Promise.allSettled([
      listDoctors({ page: 1, size: 200 }),
      listPackages({ page: 1, size: 200 })
    ])
    if (dsRes.status === 'fulfilled') {
      doctorNameMap.value = Object.fromEntries((dsRes.value.list || []).map(d => [d.doctorId, d.name]))
    }
    if (psRes.status === 'fulfilled') {
      packageNameMap.value = Object.fromEntries((psRes.value.list || []).map(p => [p.packageId, p.packageName]))
    }
  } catch (e) { /* ignore mapping errors */ }
  await fetchList()
})
</script>

<template>
  <el-card>
    <h3>我的订单</h3>
    <el-form :inline="true" :model="query" class="mb-2">
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="全部" style="width:150px">
          <el-option label="全部" value="" />
          <el-option label="待确认" :value="1" />
          <el-option label="已确认" :value="2" />
          <el-option label="已完成" :value="3" />
          <el-option label="已取消" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="类型">
        <el-select v-model="query.orderType" placeholder="全部" style="width:150px">
          <el-option label="全部" value="" />
          <el-option label="套餐" value="PACKAGE" />
          <el-option label="项目" value="INDICATOR" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="query.page=1;fetchList()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="list" v-loading="loading" style="width:100%">
      <el-table-column prop="orderId" label="体检单号" width="120" />
      <el-table-column label="体检套餐">
        <template #default="{ row }">
          <span>{{ packageNameMap[row.packageId] || (row.orderType==='INDICATOR' ? '单项体检' : '-') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="orderDate" label="体检日期" width="140" />
      <el-table-column label="医生" width="120">
        <template #default="{ row }">
          <span>{{ doctorNameMap[row.doctorId] || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="statusTagType[row.status] || 'default'" size="small">{{ statusMap[row.status] || row.status }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="260">
        <template #default="{ row }">
          <el-button type="primary" size="small" :disabled="row.status !== 3" @click="router.push({ path:'/user/results', query:{ orderId: row.orderId }})">查看报告</el-button>
          <el-button type="danger" size="small" class="ml-1" :disabled="[3,4].includes(row.status)" @click="cancelOrder(row)">取消预约</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="mt-2">
      <el-pagination background layout="total, prev, pager, next" :total="total" :page-size="query.size" :current-page="query.page" @current-change="(p)=>{query.page=p;fetchList()}" />
    </div>
  </el-card>
</template>

<style scoped>
.mb-2{ margin-bottom:12px; }
.mt-2{ margin-top:12px; }
</style>